// InvestmentDB.ts
export interface FundItem {
  // 基础信息
  code: string // 基金代码（必填）
  fullCode: string // 完整基金代码（必填）
  name?: string // 基金名称（可选）
  platform?: string // 基金所属平台（可选，如支付宝、天天基金、银行等）
  // 价格相关
  price?: number | string // 最新净值（可选）
  preClose?: number | string // 昨日净值（可选）
  change?: number | string // 涨跌幅（可选）
  // 持仓相关
  cost?: number // 成本价（可选）
  holdings?: number // 持仓数量（可选）
  fee?: number // 手续费（可选）
  // 新增计算字段
  profit?: string | number // 总盈亏
  todayProfit?: string | number // 今日盈亏
  investment?: string | number // 投入金额
  holdingValue?: string | number // 持仓金额（持仓数量 × 当前净值）
  profitRate?: string | number // 持仓盈亏率（百分比）
  // 基金特有字段
  fundType?: string // 基金类型（如股票型、债券型等）
  navDate?: string // 净值日期
  lastUpdated?: string // 最后更新时间
  // 保留扩展能力
  [key: string]: any // 允许其他属性
}
export interface StockItem {
  // 基础信息
  code: string // 股票代码（必填）
  fullCode: string // 完整股票代码（必填）
  name?: string // 股票名称（可选）
  // 价格相关
  price?: number // 最新价格（可选）
  preClose?: number // 昨收价（可选）
  change?: number | string // 涨跌幅（可选）
  // 持仓相关
  cost?: number // 成本价（可选）
  holdings?: number // 持仓数量（可选）
  tax?: number // 税费（可选）
  type?: 'stock' | 'fund' | 'convertible' // 类型区分（股票/基金/可转债）
  // 新增计算字段
  profit?: string | number // 总盈亏
  todayProfit?: string | number // 今日盈亏
  investment?: string | number // 投入金额
  holdingValue?: string | number // 持仓金额（持仓数量 × 当前价格）
  profitRate?: string | number // 持仓盈亏率（百分比）
  lastUpdated?: string // 最后更新时间
  // 保留扩展能力
  [key: string]: any // 允许其他属性
}

// 股息表数据模型接口，初始结构与股票表保持一致
export interface DividendItem extends StockItem {
  // 股息特有字段可以在这里扩展
  dividendDate?: string // 除息日
  paymentDate?: string // 派息日
  dividendAmount?: number // 每股股息金额
  dividendRate?: number // 股息率
  totalDividend?: string // 总股息收入
}

// 数据库名称
export const DB_NAME = 'InvestmentDB'
// 数据库版本
export const DB_VERSION = 1

// 打开数据库并创建存储对象
const openDB = (): Promise<IDBDatabase> => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(DB_NAME, DB_VERSION)

    request.onupgradeneeded = (event) => {
      const db = (event.target as IDBOpenDBRequest).result
      // 创建基金存储对象
      if (!db.objectStoreNames.contains('funds')) {
        db.createObjectStore('funds', { keyPath: 'code' })
      }
      // 创建股票存储对象
      if (!db.objectStoreNames.contains('stocks')) {
        db.createObjectStore('stocks', { keyPath: 'code' })
      }
      // 创建股息存储对象
      if (!db.objectStoreNames.contains('dividends')) {
        db.createObjectStore('dividends', { keyPath: 'code' })
      }
    }

    request.onsuccess = (event) => {
      resolve((event.target as IDBOpenDBRequest).result)
    }

    request.onerror = (event) => {
      console.error('打开投资数据库失败:', (event.target as IDBOpenDBRequest).error)
      reject((event.target as IDBOpenDBRequest).error)
    }
  })
}

// ===== 基金操作 =====

// 获取所有基金数据
export const getAllFunds = async (): Promise<FundItem[]> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readonly')
    const store = transaction.objectStore('funds')
    const request = store.getAll()

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error('获取基金数据失败:', request.error)
      reject(request.error)
    }
  })
}

// 根据代码获取基金
export const getFundByCode = async (code: string): Promise<FundItem | null> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readonly')
    const store = transaction.objectStore('funds')
    const request = store.get(code)

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error(`获取基金 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 添加新基金
export const addFund = async (fund: FundItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readwrite')
    const store = transaction.objectStore('funds')
    const request = store.add(fund)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`添加基金 ${fund.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 更新基金
export const updateFund = async (fund: FundItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readwrite')
    const store = transaction.objectStore('funds')
    const request = store.put(fund)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`更新基金 ${fund.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 批量更新基金
export const batchUpdateFunds = async (funds: FundItem[]): Promise<void> => {
  if (funds.length === 0) {
    return Promise.resolve()
  }

  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readwrite')
    const store = transaction.objectStore('funds')

    funds.forEach((fund) => {
      store.put(fund)
    })

    transaction.oncomplete = () => {
      console.log(`成功批量更新 ${funds.length} 条基金数据`)
      resolve()
    }

    transaction.onerror = () => {
      console.error('批量更新基金失败:', transaction.error)
      reject(transaction.error)
    }
  })
}

// 删除基金
export const deleteFund = async (code: string): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readwrite')
    const store = transaction.objectStore('funds')
    const request = store.delete(code)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`删除基金 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// ===== 股票操作 =====

// 获取所有股票数据
export const getAllStocks = async (): Promise<StockItem[]> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readonly')
    const store = transaction.objectStore('stocks')
    const request = store.getAll()

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error('获取股票数据失败:', request.error)
      reject(request.error)
    }
  })
}

// 根据代码获取股票
export const getStockByCode = async (code: string): Promise<StockItem | null> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readonly')
    const store = transaction.objectStore('stocks')
    const request = store.get(code)

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error(`获取股票 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 添加新股票
export const addStock = async (stock: StockItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readwrite')
    const store = transaction.objectStore('stocks')
    const request = store.add(stock)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`添加股票 ${stock.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 更新股票
export const updateStock = async (stock: StockItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readwrite')
    const store = transaction.objectStore('stocks')
    const request = store.put(stock)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`更新股票 ${stock.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 批量更新股票
export const batchUpdateStocks = async (stocks: StockItem[]): Promise<void> => {
  if (stocks.length === 0) {
    return Promise.resolve()
  }

  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readwrite')
    const store = transaction.objectStore('stocks')

    stocks.forEach((stock) => {
      store.put(stock)
    })

    transaction.oncomplete = () => {
      console.log(`成功批量更新 ${stocks.length} 条股票数据`)
      resolve()
    }

    transaction.onerror = () => {
      console.error('批量更新股票失败:', transaction.error)
      reject(transaction.error)
    }
  })
}

// 删除股票
export const deleteStock = async (code: string): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('stocks', 'readwrite')
    const store = transaction.objectStore('stocks')
    const request = store.delete(code)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`删除股票 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 获取所有股息数据
export const getAllDividends = async (): Promise<DividendItem[]> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('dividends', 'readonly')
    const store = transaction.objectStore('dividends')
    const request = store.getAll()

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error('获取股息数据失败:', request.error)
      reject(request.error)
    }
  })
}

// 根据代码获取股息
export const getDividendByCode = async (code: string): Promise<DividendItem | null> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('dividends', 'readonly')
    const store = transaction.objectStore('dividends')
    const request = store.get(code)

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error(`获取股息 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 添加新股息
export const addDividend = async (dividend: DividendItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('dividends', 'readwrite')
    const store = transaction.objectStore('dividends')
    const request = store.add(dividend)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`添加股息 ${dividend.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 更新股息
export const updateDividend = async (dividend: DividendItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('dividends', 'readwrite')
    const store = transaction.objectStore('dividends')
    const request = store.put(dividend)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`更新股息 ${dividend.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 批量更新股息
export const batchUpdateDividends = async (dividends: DividendItem[]): Promise<void> => {
  if (dividends.length === 0) {
    return Promise.resolve()
  }

  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('dividends', 'readwrite')
    const store = transaction.objectStore('dividends')

    dividends.forEach((dividend) => {
      store.put(dividend)
    })

    transaction.oncomplete = () => {
      console.log(`成功批量更新 ${dividends.length} 条股息数据`)
      resolve()
    }

    transaction.onerror = () => {
      console.error('批量更新股息失败:', transaction.error)
      reject(transaction.error)
    }
  })
}

// 删除股息
export const deleteDividend = async (code: string): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('dividends', 'readwrite')
    const store = transaction.objectStore('dividends')
    const request = store.delete(code)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`删除股息 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 初始化数据库（如果为空则导入初始数据）
export const initDB = async (
  initialFunds: FundItem[] = [],
  initialStocks: StockItem[] = [],
): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction(['funds', 'stocks'], 'readwrite')
    const fundStore = transaction.objectStore('funds')
    const stockStore = transaction.objectStore('stocks')

    // 先检查是否已有数据
    const fundCountRequest = fundStore.count()
    const stockCountRequest = stockStore.count()

    let fundCount = 0
    let stockCount = 0

    fundCountRequest.onsuccess = () => {
      fundCount = fundCountRequest.result
      if (fundCount === 0 && initialFunds.length > 0) {
        initialFunds.forEach((fund) => {
          fundStore.add(fund)
        })
      }
      checkComplete()
    }

    stockCountRequest.onsuccess = () => {
      stockCount = stockCountRequest.result
      if (stockCount === 0 && initialStocks.length > 0) {
        initialStocks.forEach((stock) => {
          stockStore.add(stock)
        })
      }
      checkComplete()
    }

    function checkComplete() {
      if (fundCountRequest.readyState === 'done' && stockCountRequest.readyState === 'done') {
        transaction.oncomplete = () => {
          resolve()
        }

        transaction.onerror = () => {
          console.error('初始化投资数据库失败:', transaction.error)
          reject(transaction.error)
        }
      }
    }
  })
}

// 从旧数据库迁移数据到新的投资数据库
// export const migrateFromOldDBs = async (): Promise<void> => {
//   try {
//     // 导入旧数据库操作
//     const { exportIndexedDB, importIndexedDB } = await import('./indexedDBExporter')

//     // 导出旧基金数据库数据
//     const fundData = await exportIndexedDB('FundDB')
//     // 导出旧股票数据库数据
//     const stockData = await exportIndexedDB('StockDB')

//     // 合并数据
//     const mergedData = { ...fundData, ...stockData }

//     // 导入到新数据库
//     await importIndexedDB(DB_NAME, mergedData)
//     console.log('成功从旧数据库迁移数据到投资数据库')
//   } catch (error) {
//     console.error('迁移数据失败:', error)
//     throw error
//   }
// }
